import type { ParallelTaskExecuteContext } from '../handler'

import { ParallelHandler } from '../handler'

class DecodeData extends ParallelHandler<Array<number>, AudioBuffer> {
  private audioContext: AudioContext = new AudioContext()

  public execute(
    context: ParallelTaskExecuteContext<Array<number>, AudioBuffer>,
  ): void {
    if (context.isLastExecute) {
      this.taskCompletedCallback(context.taskItem.uuid)
      return
    }

    const audioBuffer = this.audioContext.createBuffer(1, context.taskItem.original!.length, 22050)
    if (audioBuffer.copyToChannel) {
      audioBuffer.copyToChannel(new Float32Array(context.taskItem.original! as any), 0, 0)
    }

    this.forwardToHandler(audioBuffer)
    this.taskCompletedCallback(context.taskItem.uuid)
  }

  protected onFinish(): void {
    if (this.audioContext) {
      this.audioContext.suspend()
      this.audioContext = new AudioContext()
    }
    this.executeController?.$bus.emit('_decodeDataFinish')
  }
}

export default DecodeData
